﻿using System;
using System.Text;
using System.Text.RegularExpressions;

namespace VSSDKAssist.Assets.Helpers.KeyRegistration
{
	public sealed class PLKRegistrator : Registrator
	{
		public PLKRegistrator(
			string companyName,
			string packageName,
			Guid packageGuid,
			string packageVersion,
			MinimumProductEdition minimumProductEdition,
			MinimumVSVersion minimumVSVersion)
			: base(companyName, packageName, packageGuid, packageVersion)
		{
			this.MinimumProductEdition = minimumProductEdition;
			this.MinimumVSVersion = minimumVSVersion;
		}

		public MinimumProductEdition MinimumProductEdition { get; set; }
		public MinimumVSVersion MinimumVSVersion { get; set; }

		protected override string GetKey(string aspxPage)
		{
			string response = string.Empty;

			Regex reg = new Regex(
				".*Package Load Key \\(PLK\\)</b></td><td>(?<PLK>.*)</td></tr>.*",
				RegexOptions.Compiled | RegexOptions.IgnoreCase);

			if(reg.IsMatch(aspxPage))
			{
				response = reg.Match(aspxPage).Groups["PLK"].Value;
				response = response.Replace("<br>", string.Empty).Trim();
			}

			return response;
		}

		protected override string GetPostData(string aspxPage)
		{
			StringBuilder postData = new StringBuilder();

			postData.Append(base.GetPostData(aspxPage));

			postData.Append(string.Format("__EVENTTARGET={0}&", GetDoPostBackName(aspxPage, "btnSave")));
			postData.Append(string.Format("{0}={1}&", GetInputName(aspxPage, "txtCompanyName"), this.CompanyName));
			postData.Append(string.Format("{0}={1}&", GetInputName(aspxPage, "txtPackageName"), this.Name));
			postData.Append(string.Format("{0}={1}&", GetInputName(aspxPage, "txtPackageGuid"), this.Guid.ToString("D")));
			postData.Append(string.Format("{0}={1}&", GetInputName(aspxPage, "txtPackageVersion"), this.Version));
			postData.Append(string.Format("{0}={1}&", GetInputName(aspxPage, "ddlProductEdition"), (int)this.MinimumProductEdition));
			postData.Append(string.Format("{0}={1}&", GetInputName(aspxPage, "ddlVSVersion"), (int)this.MinimumVSVersion));

			return postData.ToString();
		}
	}
}
